/********************************
/*Chuong trinh Server lan chat
********************************/

#include"iostream"
#include <tchar.h>
#include <winsock2.h>

using namespace std;
#pragma comment (lib,"ws2_32.lib")


int main()
{
	struct hostent* serverHostent;
	char Datasend[1024];
	char Datarec[1024]={0};
	WSADATA SData;
	char hostName[256];
    int iResult = WSAStartup(0x0202,&SData);
    if (iResult != 0)
    {
        cout<<"Khoi dong winsock khong thanh cong, errorcode: "<<WSAGetLastError();	//thong bao loi
		system("pause");
        return 1;
    }

    cout <<"Khoi dong winsock thanh cong!\n";
    cout <<"Phien ban: "<< SData.wVersion << "\n";  
    cout <<"Phien ban co the ho tro: "<< SData.wHighVersion << "\n";
    cout <<"Ghi chu: " << SData.szDescription << "\n";
    cout <<"Thong tin cau hinh: " << SData.szSystemStatus << "\n";
	cout<<"\n===============================================================\n";

	//------Khoi tao socket
	SOCKET ServerSock;
	ServerSock= socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
	if(ServerSock!=INVALID_SOCKET)
		cout<<"\nKhoi tao socket thanh cong!!!\n";
	else
	{
		cout<<"\nKhong khoi tao duoc socket! Error code: "<<WSAGetLastError()<<"\n";
		system("pause");
		return 1;
	}

	sockaddr_in ServerAdd;
	memset(&ServerAdd,0,sizeof(ServerAdd));
    ServerAdd.sin_family=AF_INET;
    ServerAdd.sin_port=htons(1234);
    ServerAdd.sin_addr.s_addr=htonl(INADDR_ANY);
    int nResult=bind(ServerSock,(sockaddr*)&ServerAdd,sizeof(ServerAdd));
	if(nResult==-1)
	{
		cout<<"Loi khi thiet lap IP va Port\n";
		WSAGetLastError();
        closesocket(ServerSock);
		system("PAUSE");
        return 1;
	}
	else
		cout<<"Dang doi may Client...\n\n";
	while(1)
	{
		int nSizeAddr = sizeof(ServerAdd);        // xac dinh kich thuoc serverAdd
		while(1)
		{
			memset(Datarec,0,sizeof(Datarec));
			int kq=recvfrom(ServerSock,Datarec,sizeof(Datarec),0,(sockaddr*)&ServerAdd,&nSizeAddr);
			if(kq>0)
			{
				cout<<">>Client Noi: "<<Datarec;
				cout<<"\n>Moi ban nhap: ";
				cin.getline(Datasend,200);
				sendto(ServerSock,Datasend,sizeof(Datasend),0,(sockaddr*)&ServerAdd,sizeof(ServerAdd));
			}
			else
			{
				cout<<"\n>Moi ban nhap: ";
				cin.getline(Datasend,200);
				sendto(ServerSock,Datasend,sizeof(Datasend),0,(sockaddr*)&ServerAdd,sizeof(ServerAdd));
			}
		}

        closesocket(ServerSock);
	}
    WSACleanup();
    setsockopt;
	system("PAUSE");
	return 1;
}